package com.learn.core.controller.learn;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.*;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.LDetails;
import com.learn.core.domain.LOrganization;
import com.learn.core.domain.LUser;
import com.learn.core.domain.view.UserDetailsGather;
import com.learn.core.service.ILDetailsService;
import com.learn.core.service.ILOrganizationService;
import com.learn.core.service.ILUserService;
import com.learn.core.service.IUserDetailsGatherService;
import com.learn.core.vo.LoginVO;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @auther CodeGenerator
 * @create 2021-03-08 22:50:00
 * @describe 用户表前端控制器
 */
@Api("用户")
@RestController
@RequestMapping("/learn/user")
public class LoginController extends WebController<LUser> {

    @Autowired
    private ILUserService ilUserService;
    @Autowired
    private IUserDetailsGatherService iUserDetailsGatherService;
    @Autowired
    private ILDetailsService ilDetailsService;
    @Autowired
    private ILOrganizationService ilOrganizationService;

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    //注册
    @ApiOperation(value = "注册")
    @PostMapping("/register")
    public CommonResult<Object> register(@RequestBody LUser luser){
        try {
            if(luser==null){
                return (CommonResult) ResultUtil.error(ResultEnum.REGISTER_FAIL);
            }
            if(StringUtils.isNotEmpty(luser.getUserName())){
                QueryWrapper<LUser> queryWrapper = new QueryWrapper<LUser>();
                queryWrapper.eq("user_name", luser.getUserName());
                if(ilUserService.getOne(queryWrapper)!=null) return (CommonResult) ResultUtil.error(ResultEnum.ACCOUNT_EXIST);
            }else{
                return (CommonResult) ResultUtil.error(ResultEnum.NOT_ACCOUNT);
            }
            if(StringUtils.isEmpty(luser.getPassword())){
                return (CommonResult) ResultUtil.error(ResultEnum.NOT_PASSWORD);
            }
            if(StringUtils.isNotEmpty(luser.getMobile())){
                QueryWrapper<LUser> queryWrapper = new QueryWrapper<LUser>();
                queryWrapper.eq("mobile", luser.getMobile());
                if(ilUserService.getOne(queryWrapper)!=null) return (CommonResult) ResultUtil.error(ResultEnum.MOBILE_EXIST);
            }else{
                return  (CommonResult) ResultUtil.error(ResultEnum.NOT_MOBILE);
            }
            if(StringUtils.isEmpty(luser.getStutes()))
                luser.setStutes("1");
            //TODO 注册的用户需要增加角色，通过注册的用户只能是学员，不能进入后台管理，企业自己得员工需要管理员在后台增加
            LDetails lDetails = new LDetails();
            lDetails.setRoleId(30);
            lDetails.setCreateTime(new Date());
            //TODO 注册的用户机构需要默认添加，而且机构为制定机构，是专门学习机构，需要后续制定
            lDetails.setOrganizationId(88);
            if(ilDetailsService.save(lDetails)){
                luser.setDetailsId(lDetails.getDetailsId());
                luser.setCreateTime(new Date());
                luser.setPassword(Md5Utils.hash(luser.getPassword()));
                if(ilUserService.save(luser)){
                    return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }

        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //登录
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public CommonResult<Object> login(@RequestBody  LUser luser){
        try {
            QueryWrapper<LUser> queryWrapper = new QueryWrapper<LUser>();
            queryWrapper.eq("user_name", luser.getUserName());
            LUser userForBase= ilUserService.getOne(queryWrapper);
            if(userForBase==null){
                return (CommonResult) ResultUtil.error(ResultEnum.NOT_ACCOUNT);
            }else {
                if("0".equals(userForBase.getStutes())){
                    return (CommonResult) ResultUtil.error(ResultEnum.ACCOUNT_IS_FORBID);
                }else if(!userForBase.getPassword().equals(Md5Utils.hash(luser.getPassword()))){
                    return (CommonResult) ResultUtil.error(ResultEnum.PASSWORD_ERROR);
                }else {
                    String token = JwtUtil.sign(userForBase.getUserName(),userForBase.getUserId().toString());

                    QueryWrapper<UserDetailsGather> userDetailsGatherQueryWrapper = new QueryWrapper<>();
                    userDetailsGatherQueryWrapper.eq("user_id", userForBase.getUserId());
                    UserDetailsGather userDetailsGather = iUserDetailsGatherService.getOne(userDetailsGatherQueryWrapper);

                    LoginVO loginVO = new LoginVO(token,userDetailsGather);
                    return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS,loginVO);
                }
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //用户个人信息
    @ApiOperation(value = "用户个人信息")
    @UserLoginToken
    @GetMapping("/info")
    public CommonResult<Object> info( @RequestParam("id")String userId){
        try {
            if (userId==null){
                return (CommonResult) ResultUtil.error(ResultEnum.LOAD_ERROR);
            }
            QueryWrapper<UserDetailsGather> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId);
            UserDetailsGather lUsers = iUserDetailsGatherService.getOne(queryWrapper);
            LOrganization lOrganization = ilOrganizationService.getById(lUsers.getOrganizationId());
            if(null != lOrganization)
                lUsers.setOrganizationName(lOrganization.getOrganizationName());
            // 返回
            return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS,lUsers);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //更新
    @ApiOperation(value = "更新")
    @PostMapping("/edit")
    @UserLoginToken
    public CommonResult<Object> edit(@RequestBody UserDetailsGather userDetailsGather) {
        if(userDetailsGather!=null){
            LUser lUser = new LUser();
            lUser.setUserId(userDetailsGather.getUserId());
            if(StringUtils.isNotEmpty(userDetailsGather.getUserName()))
                lUser.setUserName(userDetailsGather.getUserName());
            if(StringUtils.isNotEmpty(userDetailsGather.getEmail()))
                lUser.setEmail(userDetailsGather.getEmail());
            if(ilUserService.updateById(lUser)){
                LDetails lDetails = new LDetails();
                lDetails.setDetailsId(userDetailsGather.getDetailsId());
                if(StringUtils.isNotEmpty(userDetailsGather.getName()))
                    lDetails.setName(userDetailsGather.getName());
                if(StringUtils.isNotEmpty(userDetailsGather.getSex()))
                    lDetails.setSex(userDetailsGather.getSex());
                if(StringUtils.isNotEmpty(userDetailsGather.getCardId()))
                    lDetails.setCardId(userDetailsGather.getCardId());
                if(StringUtils.isNotEmpty(userDetailsGather.getBirthTime()))
                    lDetails.setBirthTime(formatter.format(userDetailsGather.getBirthTime()));
                if(StringUtils.isNotEmpty(userDetailsGather.getEntryTime()))
                    lDetails.setEntryTime(userDetailsGather.getEntryTime());
                if(StringUtils.isNotEmpty(userDetailsGather.getNation()))
                    lDetails.setNation(userDetailsGather.getNation());
                if(StringUtils.isNotEmpty(userDetailsGather.getEducationId()))
                    lDetails.setEducationId(userDetailsGather.getEducationId());
                if(StringUtils.isNotEmpty(userDetailsGather.getUserCover()))
                    lDetails.setUserCover(userDetailsGather.getUserCover());
                ilDetailsService.updateById(lDetails);
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    //更新密码
    @ApiOperation(value = "更新密码")
    @PostMapping("/password")
    @UserLoginToken
    public CommonResult<Object> password(@RequestBody LUser lUser) {
        if(lUser!=null){
            if(StringUtils.isEmpty(lUser.getUserId()))
                return (CommonResult) ResultUtil.error(ResultEnum.LOAD_ERROR);
            LUser user = ilUserService.getById(lUser.getUserId());
            if(!Md5Utils.hash(lUser.getPassword()).equals(user.getPassword()))
                return (CommonResult) ResultUtil.error(ResultEnum.PASSWORD_ERROR);
            lUser.setPassword(Md5Utils.hash(lUser.getNewPassword()));
            if(ilUserService.updateById(lUser)){
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }
}

